<%@ page language="java" contentType="text/html; charset=UTF-8"
		 pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<title>${app} 测试应用</title>
    <jsp:include page="common/common_head.jsp"></jsp:include>

    <jsp:include page="common/common_editor.jsp"/>

</head>
<body  data-spy="scroll" data-target=".navbar">



<jsp:include page="common/common_banner_app.jsp"></jsp:include>
<div style="height:30px"></div>
<div class="container">


    <h4>${name} [${host}]

        <c:if test="${deployVersion}">
            <span id="appInstalledTrue"  <c:if test="${!installed}">style="display: none"</c:if>>

            <div  class="input-prepend">
                <a type="button" class="btn " onclick="update()">
                    更新
                </a>

                <a class="btn " href="#" onclick="setLogPath()">
                    日志目录</a>
                <a class="btn btn-primary" href="/appManager/appManagerLogList.html?appName=${name}&host=${host}">
                    查看文件</a>


            </div>
            <div class="input-prepend">


                &nbsp;
                <span class="add-on">版本</span>
                <c:if test="${ not empty maxTag}">

                    版本: <select id="tag" style="width: 80px">
                    <c:forEach items="${tag}" var="c" >
                        <option>${c}</option>
                    </c:forEach>
                </select>

                </c:if>
                <input  class="span2" id="newTag" type="text" placeholder="新版本"  style="width: 80px">
                <input  class="span2" id="describe" type="text" placeholder="版本说明" style="width: 80px">
                <input  type="button" class="btn btn-primary" onclick="tag()" value="发布新版本">

            </div>

        </span>

        <span id="appInstalledFalse" <c:if test="${installed}">style="display: none"</c:if>>
             <input type="button" onclick="install()"  class="btn"  value="安装">
            <input type="button" onclick="stopFun()"  class="btn" value="停止">
        </span>


        </c:if>


    </h4>

        <div id="moduleTable">


        </div>

    <div>


        <textarea style="width:100%;height: 800px" id="area" ></textarea>
    </div>




	<jsp:include page="common/common_js.jsp"></jsp:include>




    <script type="text/javascript" src="/js/manager.js"></script>
    <script type="text/javascript" src="/js/log.js"></script>

	<script>

        window.stop = true;
        var logPath = "";

        function setLogPath(){
            var path = prompt("当前目录" + logPath).trim()
            if(path != "") logPath = path;
        }

        function stopFun(){stop = true;}

        function update(){
            $.ajax({
                url: "/test/update.html",
                data: {name: '${name}', host: '${host}'},
                dataType: "json",
                success: function(r){

                    if(r.taskId != ""){

                        stop = false
                        showLog("area", r.taskId, "${host}")
                    }
                }

            })
        }

        function install(){
            $.ajax({
                url: "/test/install.html",
                data: {name: '${name}', host: '${host}'},
                dataType: "json",
                success: function(r){

                    if(r.taskId != ""){

                        stop = false
                        showLog("area", r.taskId, "${host}", "install")
                    }
                }

            })
        }

        function tag(){
            var tag = $("#newTag").val()
            var describe = $("#describe").val()

            if(describe == "") describe = new Date().Format("yyyy/MM/dd-hh:mm:ss");
            if(tag == "" || tag < "${maxTag}"){
                alert("版本号不正确!")
                return
            }

            $.ajax({
                url: "/test/manager.html",
                data: {name: '${name}', host: '${host}', action: "tag " + tag + " " + describe },
                dataType: "json",
                success: function(r){

                    if(r.taskId != ""){

                        stop = false
                        showLog("area", r.taskId, "${host}", "tag")
                    }
                }

            })
        }

        var id = 0;
        function actionAndLog(reqUrl, action, module, btnId){

            if(stop == false){
                alert("有任务正在执行,请稍等!!");
                return;
            }
            editor.doc.setValue("任务开始执行 " + module + " " + action + "\n");
            $.ajax({
                url: reqUrl,
                dataType: "json",
                success: function(r){

                    if(r.taskId != ""){

                        stop = false
                        showLogByTaskId({
                            taskId: r.taskId,
                            hostName: "${host}",
                            action: action,
                            offset: -1,
                            id: 0,
                            render: function(r, config){

                                if(r.message != ""){
//                                    var obj = $("#" + config.targetId);
//                                if(config.offset < 0 )
//                                    html = r.message
//                                else{
                                    var html = editor.doc.getValue();
                                    if(html.length > logMaxLen){
                                        html = html.substring(logMaxLen / 2, html.length) + r.message
                                    }else{
                                        html = html + r.message
                                    }
                                    //}

                                    var top =  autoScroll()
                                    editor.doc.setValue(html)
                                    editor.scrollTo(-1, top)
                                }


                                if(config.reqNum % 2 == 0){
                                    $(".CodeMirror").css("border", "1px solid white")
                                }else{
                                    $(".CodeMirror").css("border", "1px solid green")

                                }
                            },
                            error: function(){

                                $(".CodeMirror").css("border", "1px solid red")

                            },
                            complete: function(config){

                                var action = config.action;
                                if(action == "start" || action == "stop" ||
                                        action == "stop_9" || action == "all"
                                        || action == "install" || action == "update"){

                                    check();

                                }
                                $(".CodeMirror").css("border", "1px solid green")

                                if(action == "start" || action == "all" || action == "restart" ){

                                    setTimeout(function(){
                                        log('${name}','${host}','logs/' + module + ".log",null,true, btnId, -1, false)
                                    }, 200)

                                }else{
                                    stop = true;
                                }

                            }
                        })
                        //showLog("area", r.taskId, "${host}", action)
                    }
                }

            })
        }


        var lastLogBtnId = null;
        function changeLogFun(btnId){
            var btnObj = $("#" + btnId)

            if(btnObj.attr("title") == "查看日志"){
                btnObj.attr("title","停止")
                btnObj.addClass("btn-success")
                stop = false
                lastLogBtnId = btnId;

            }else{
                stop = true
                btnObj.attr("title","查看日志")
                btnObj.removeClass("btn-success")
                lastLogBtnId = null;

            }
        }


        function log(appName,host,path,id,first, btnId, offset, clean){

            if(logPath != "") path = logPath;

            tail({
                appName: appName,
                host: host,
                path: path,
                id: id,
                first: first,
                btnId: btnId,
                offset: offset,
                clean: clean,
                lastLogBtnId: null,
                lastOffset: 0,
                before: function(config){

                    if(config.first){

                        var localLastBtnId = lastLogBtnId;
                        config.lastOffset = 0;
                        if(lastLogBtnId != null) changeLogFun(lastLogBtnId)

                        //是否正在执行
                        if(localLastBtnId != config.btnId){
                            changeLogFun(config.btnId)
                            if(typeof config.clean == "undefined" || config.clean == true)
                                editor.doc.setValue("");
                        }
                        config.first = false;
                    }
                    if(lastLogBtnId != config.btnId) return false;
                    else return true;
                },
                render: function(r, config){

                    if(r.message != ""){
                        var html = editor.doc.getValue();
                        if(html.length > logMaxLen){
                            html = html.substring(logMaxLen / 2, html.length) + r.message
                        }else{
                            html = html + r.message
                        }

                        var top =  autoScroll()
                        editor.doc.setValue(html)
                        editor.scrollTo(-1, top)
                    }


//                    console.info(config.reqNum)
//                    if(config.reqNum % 2 == 0){
//                        $(".CodeMirror").css("border", "1px solid white")
//                    }else{
//                        $(".CodeMirror").css("border", "1px solid green")
//
//                    }
                },
                success: function(config){

                }


            })
            //var logPath = $("#logPath").val();




            //val url = "appManager/appManagerLogDetail.html?appName=zookeeper&host=fbj.local&path=//build.xml&type=json"
//
//
//            $.ajax({
//                url: "/appManager/appManagerLogDetail.html",
//                data: {appName: appName, host: host, path: path, type: "json", offset: offset || -1, size: 4000},
//                dataType: "json",
//                success: function(r){
//
//                    if(r[0].message != ""){
//
//                        //var target = $("#" + id)
//                        //var content = target.html()
////                        var len = content.length
////                        var max = 1000000
////                        if(len > max)
////                            content = content.substring(len - max, len)
//                        //target.html(content + "\n" + r[0].message)
////                        target.html(r[0].message)
////                        if(autoScroll(target))
////                            target.scrollTop(target[0].scrollHeight);
////                        SyntaxHighlighter.all()
//
//
//                            var html = editor.doc.getValue();
//                            if(html.length > logMaxLen){
//                                html = html.substring(logMaxLen / 2, html.length) + r[0].message
//                            }else{
//                                html = html + r[0].message
//                            }
//
//                        var top =  autoScroll()
//                        editor.doc.setValue(html)
//                        editor.scrollTo(-1, top)
//                            //editor.scrollTo()
//
//                    }
//
//
//
//                }
//
//            })
        }

        var i = 0;
        //通过taskId获取日志
        function showLog(id, taskId,host,action){

                    $.ajax({
                        url: "/test/taskLog.html",
                        data: {taskId: taskId, host: host},
                        dataType: "json",
                        success: function(r){

                                if(r[0].message != ""){

//                                    var content = $("#" + id).html()
//                                    var len = content.length
//                                    var max = 1000000
//                                    if(len > max)
//                                        content = content.substring(len - max, len)
//                                    $("#" + id).html(content + "\n" + r[0].message)
//                                    var target = $("#" + id)
//                                    target.html( r[0].message)
//                                    if(autoScroll(target))
//                                        target.scrollTop(target[0].scrollHeight);
//                                    SyntaxHighlighter.all()

                                    var top =  autoScroll()
                                    editor.doc.setValue(r[0].message)
                                    editor.scrollTo(-1, top)




                                }
                                if(!r[0].status.finished && stop == false){

                                    i++;
                                    if(i % 2 == 0){
                                        $(".CodeMirror").css("border", "1px solid white")
                                    }else{
                                        $(".CodeMirror").css("border", "1px solid #ccc")

                                    }
                                    setTimeout(function(){showLog(id, taskId, host,action)}, 500)
                                }else{
                                    if(action == "start" || action == "stop" ||
                                            action == "stop_9" || action == "all"
                                        || action == "install" || action == "update"){

                                        check();

                                    }
                                    stop = true;
                                    $(".CodeMirror").css("border", "1px solid green")
                                }

                        }

                    })
        }


        function autoScroll(){
//            Object {left: 0, top: 308, height: 1123, width: 1153, clientHeight: 800…}
//            clientHeight: 800
//            clientWidth: 1153
//            height: 1123
//            left: 0
//            top: 308
//            width: 1153
            var obj = editor.getScrollInfo()
            var viewH = obj.clientHeight;//可见高
            var contentH = obj.height;//内容高度
            var scrollTop = obj.top;//滚动高度
            if(scrollTop == 0 || (contentH - viewH - scrollTop <= 100)) { //到达底部100px时,加载新内容
                //if(scrollTop/(contentH -viewH)>=0.95){ //到达底部100px时,加载新内容
                //return true;
                return contentH
            }else{
                return scrollTop
            }

        }

        function reSizeHeight(){

            var obj = $("#moduleTable")[0]

            var height = window.screen.availHeight - (obj.clientHeight + obj.offsetTop + 150)
            editor.setSize(-1,height)

        }


        var editor = null;

        function check(){
            checkModule('${name}', '${host}', {
                complete: function(r){
                    if(r.length > 0){
                        $("#appInstalledTrue").css("display","")
                        $("#appInstalledFalse").css("display","none")
                    }
                    reSizeHeight();
                },
                targetId: "moduleTable"
            });
        }


        $(document).ready(function(){

            check();


            editor = CodeMirror.fromTextArea(document.getElementById("area"), {
                mode: "shell",
                indentWithTabs: true,
                smartIndent: true,
                lineNumbers: true,
                lineWrapping: true,
                matchBrackets : true,
                autofocus: true,
                height: "1000",
                lines: 300,
                theme: "eclipse",
                styleActiveLine: true,
                extraKeys: {
                    //"Ctrl-.": "autocomplete",
                    //"Ctrl-Enter": function(){search()},
                    "F10": function(cm) {
                        if(cm.getOption("fullScreen")){
                            $(".navbar").css("display", "");
                            cm.setOption("theme", "eclipse");

                        }else{
                            cm.setOption("theme", "midnight");
                            $(".navbar").css("display", "none")

                        }
                        cm.setOption("fullScreen", !cm.getOption("fullScreen"));

                    }

                },
                hintOptions: {tables: {
                    users: {name: null, score: null, birthDate: null},
                    countries: {name: null, population: null, size: null}
                }}
            });

        })



	</script>
</body>
</html>